package com.rxy.api;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

public class CreateNode implements Watcher {

    // 计数工具类，让线程处于等待阻塞，主要不让main方法结束
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws Exception {
        // 客户端可以通过创建一个zk实例来连接zk服务器
        zooKeeper = new ZooKeeper("192.168.31.247:2181",
                5000, new CreateNode());
        // 让会话一直保持着
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        // 当连接创建了，服务端发送给客户端SyncConnected事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            //调用创建节点方法
            try {
                createNodeSync();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void createNodeSync() throws Exception {
        /**
         * 创建节点方法：
         * String node = zookeeper.create(path,data,acl,createMode);
         *   path：节点创建的路径
         *   data[]：节点创建要保存的数据，是个byte类型的
         *   acl：节点创建的权限信息(4种类型)
         *     ANYONE_ID_UNSAFE：表示任何⼈
         *     AUTH_IDS：此ID仅可⽤于设置ACL。它将被客户机验证的ID替换
         *     OPEN_ACL_UNSAFE：这是⼀个完全开放的ACL(常⽤)-->world:anyone
         *     CREATOR_ALL_ACL：此ACL授予创建者身份验证ID的所有权限
         *   createMode：创建节点的类型(4种类型)
         *     PERSISTENT：持久节点
         *     PERSISTENT_SEQUENTIAL：持久顺序节点
         *     EPHEMERAL：临时节点
         *     EPHEMERAL_SEQUENTIAL：临时顺序节点
         */
        String node_persistent = zooKeeper.create("/rxy-persistent",
                "持久节点内容".getBytes("utf-8"),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        String node_epersistent = zooKeeper.create("/rxy_ephemeral",
                "临时节点内容".getBytes("utf-8"),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        String node_persistent_sequential = zooKeeper.create("/rxy_persistent_sequential",
                "持久顺序节点内容".getBytes("utf-8"),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        System.out.println("创建的持久节点:"+node_persistent);
        System.out.println("创建的临时节点:"+node_epersistent);
        System.out.println("创建的持久顺序节点:"+node_persistent_sequential);
    }
}
